const { Controller } = require('egg')
const dayjs = require('dayjs')

class ApiController extends Controller {
  /**
   * @api {get} /query/base-info [一键查查] 人员基本信息
   * @apiGroup Query
   * 
   * @apiDescription 一键查查-人员基本信息
   * 
   * @apiParam {String} idCard 身份证号码
   * 
   * @apiSuccessExample {json} Success-Response:
  {
      "code": 0,
      "msg": "success",
      "data": {
          "name": "吴俊河", // 姓名
          "tel": "13506988175", // 电话
          "createTime": "2022-12-03 15:18:50",
          "idCard": "412721********5057",
          "sfczrq": "否", // 是否常住人口
          "address": "包屯镇" // 地址
      }
  }
   */
  async baseInfo() {
    const { ctx, app } = this
    const { knex } = app
    const { helper, query } = ctx
    const { idCard } = query
    const { TABLE_PERSON } = this.config.constant

    helper.validate(query, {
      required: ['idCard'],
    })

    const person = await knex(TABLE_PERSON)
      .where({
        cardno: idCard,
      })
      .limit(1)
      .orderBy('id', 'DESC')
      .then(doc => {
        if (!doc || !doc.length) throw '暂无相关信息'

        return doc[0]
      })

    const returnData = {
      name: person.username,
      tel: person.tel,
      createTime: dayjs(person.djtime || person.create_time).format('YYYY-MM-DD HH:mm:ss'),
      idCard: idCardFormat(idCard),
      sfczrq: person.sfczrq || '否',
      address: person.area,
    }

    ctx.body = {
      code: 0,
      msg: 'success',
      data: returnData,
    }
  }

  /**
   * @api {get} /query/hs-result [一键查查] 核酸检测信息
   * @apiGroup Query
   * 
   * @apiDescription 一键查查-核酸检测信息
   * 
   * @apiParam {String} idCard 身份证号码
   * 
   * @apiSuccessExample {json} Success-Response:
  {
      "code": 0,
      "msg": "success",
      "data": [
          {
            "checkStatus": "阴性", // 核酸结果
            "collectTime": "2022-12-08 00:00:00", // 采集时间
            "checkTime": "2022-12-07 00:42:39", // 检查时间
            "company": "机构名称", // 机构名称
            "address": "乡镇3" // 检查地点
          },
        ]
    }
   */
  async hsResult() {
    const { ctx, app } = this
    const { knex } = app
    const { helper, query } = ctx
    const { idCard } = query
    const { TABLE_HS_RESULT } = this.config.constant

    helper.validate(query, {
      required: ['idCard'],
    })

    const returnData = await knex(TABLE_HS_RESULT)
      .where({
        yw_id_card: idCard,
      })
      .limit(100)
      .orderBy('id', 'DESC')
      .then(res => {
        if (!res || !res.length) throw '暂无相关信息'

        return res.map(item => {
          return {
            checkStatus: item.yw_check_status,
            collectTime: dayjs(item.yw_sampling_time).format('YYYY-MM-DD HH:mm:ss'),
            checkTime: dayjs(item.YW_REPORT_TIME).format('YYYY-MM-DD HH:mm:ss'),
            company: item.yw_agency_serial_code,
            address: item.yw_check_city_id,
          }
        })
      })

    console.log('returnData', returnData)

    ctx.body = {
      code: 0,
      msg: 'success',
      data: returnData,
    }
  }

  /**
   * @api {get} /query/probably [一键查查] 密接
   * @apiGroup Query
   * 
   * @apiDescription 一键查查-密接信息
   * 
   * @apiParam {String} idCard 身份证号码
   * 
   * @apiSuccessExample {json} Success-Response:
  {
      "code": 0,
      "msg": "success",
      "data": [
          {
              "yxryname": "吴俊河", // 阳性人员
              "yxcardno": "512345678913456782", // 阳性人员证件号码
              "yyxbrgx": "夫妻", // 与阳性人员关系
              "jccardno": "512345678913456782", // 接触人证件号码
              "jcname": "单航", // 接触人姓名
              "jzdz": null, // 接触地点
              "jcjg": null, // 处理方式
              "jcsj": "2022-11-28 00:00:00" // 与阳性人员关系接触时间
          }
      ]
  }
   */
  async probably() {
    const { ctx, app } = this
    const { knex } = app
    const { helper, query } = ctx
    const { idCard } = query
    const { TABLE_PROBABLY } = this.config.constant

    helper.validate(query, {
      required: ['idCard'],
    })

    const returnData = await knex(TABLE_PROBABLY)
      .where({
        yxcardno: idCard,
      })
      .orderBy('id', 'DESC')
      .then(doc => {
        if (!doc || !doc.length) throw '暂无相关信息'

        return doc.map(item => {
          return {
            yxryname: item.yxryname,
            yxcardno: item.yxcardno,
            yyxbrgx: item.yyxbrgx,
            jccardno: item.jccardno,
            jcname: item.jcname,
            jzdz: item.jcdd,
            jcjg: item.jcjg,
            jcsj: dayjs(item.jcsj).format('YYYY-MM-DD HH:mm:ss'),
          }
        })
      })

    ctx.body = {
      code: 0,
      msg: 'success',
      data: returnData,
    }
  }

  /**
   * @api {get} /query/isolate [一键查查] 集中和居家隔离信息
   * @apiGroup Query
   * 
   * @apiDescription 一键查查-集中和居家隔离信息
   * 
   * @apiParam {String} idCard 身份证号码
   * 
   * @apiSuccessExample {json} Success-Response:
  {
      "code": 0,
      "msg": "success",
      "data": [
          {
              "name": "王占强", // 隔离人员
              "idCard": "512345678913456782", // 隔离人员证件号
              "isolateType": "居家隔离", // 隔离方式
              "startTime": "2020-11-14 00:00:00", // 开始隔离时间
              "endTime": "2020-11-14 00:00:00" // 接触隔离时间
          }
      ]
  }
   */
  async isolate() {
    const { ctx, app } = this
    const { knex } = app
    const { helper, query } = ctx
    const { idCard } = query
    const { TABLE_JJGL } = this.config.constant

    helper.validate(query, {
      required: ['idCard'],
    })

    const returnData = await knex(TABLE_JJGL)
      .where({
        cardno: idCard,
      })
      .orderBy('id', 'DESC')
      .then(doc => {
        if (!doc || !doc.length) throw '暂无相关信息'

        return doc.map(item => {
          console.log('item', item)

          return {
            name: item.username,
            idCard: item.cardno,
            isolateType: '居家隔离',
            startTime: item.glkssj ? dayjs(item.glkssj).format('YYYY-MM-DD HH:mm:ss') : null,
            endTime: item.lktime ? dayjs(item.lktime).format('YYYY-MM-DD HH:mm:ss') : null,
          }
        })
      })

    ctx.body = {
      code: 0,
      msg: 'success',
      data: returnData,
    }
  }

  /**
   * @api {get} /query/scan [一键查查] 场所出入信息
   * @apiGroup Query
   * 
   * @apiDescription 一键查查-场所出入信息
   * 
   * @apiParam {String} idCard 身份证号码
   * 
   * @apiSuccessExample {json} Success-Response:
  {
      "code": 0,
      "msg": "success",
      "data": [
          {
              "placeLocation": null, // 场所位置
              "placeType": 1, // 场所类型
              "placeName": "场所名称1", // 场所名称
              "scanTime": "2022-12-07 00:00:00", // 场所名称
              "codeStatus": null // 健康码状态
          }
      ]
  }
   */
  async scan() {
    const { ctx, app } = this
    const { knex } = app
    const { dict } = this.config
    const { helper, query } = ctx
    const { idCard } = query
    const { TABLE_SCAN_RECORD } = this.config.constant

    helper.validate(query, {
      required: ['idCard'],
    })

    const returnData = await knex(TABLE_SCAN_RECORD)
      .where({
        card_no: idCard,
      })
      .orderBy('id', 'DESC')
      .then(doc => {
        if (!doc || !doc.length) throw '暂无相关信息'

        return doc.map(item => {
          return {
            placeLocation: item.place_location,
            placeType: dict.placeTypeValues[item.cstype],
            placeName: item.place_name,
            scanTime: item.scancode_date ? dayjs(item.scancode_date).format('YYYY-MM-DD HH:mm:ss') : null,
            codeStatus: item.healthcode_status || '绿码',
          }
        })
      })

    ctx.body = {
      code: 0,
      msg: 'success',
      data: returnData,
    }
  }
}

function idCardFormat(data) {
  if (!data) data = ''
  return data.replace(/(.{6}).*(.{4})/, '$1********$2')
}

module.exports = ApiController
